package com.topcheer.common.auth.interceptor;

import com.topcheer.common.auth.config.UserAuthConfig;
import com.topcheer.common.auth.context.BaseContextHandler;
import com.topcheer.common.auth.feign.RbacService;
import com.topcheer.common.auth.jwt.JwtHelper;
import com.topcheer.common.auth.user.JwtUser;
import com.topcheer.common.base.CommonConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author xutao
 * @Package com.example.baseline.rbac.interceptor
 * @Description: ${todo}
 * @date 2020/3/30 14:41
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired(required = false)
    private RbacService rbacService;

    @Autowired
    UserAuthConfig userAuthConfig;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String token = request.getHeader(userAuthConfig.getTokenHeader());
        if (!StringUtils.isEmpty(token)) {
            String username = JwtHelper.getUsernameFromToken(token,userAuthConfig.getPubKeyByte());
            if (username != null ){
                JwtUser jwtUser = rbacService.getJwtUser(username).getData();
                if (jwtUser !=null && JwtHelper.validateToken(token, jwtUser,userAuthConfig.getPubKeyByte())){
                    BaseContextHandler.setUserID(jwtUser.getUserId());
                    BaseContextHandler.setUsername(jwtUser.getUserName());
                    BaseContextHandler.set(CommonConstants.ROLE_LIST,jwtUser.getRoleList());
                    BaseContextHandler.set(CommonConstants.ORG_ID,jwtUser.getOrgId());
//                    BaseContextHandler.set(CommonConstants.ROLE_LIST,userDetails.getAuthorities());
                    BaseContextHandler.setToken(token);
                }
            }
        }
        chain.doFilter(request, response);
    }
}
